/*
Copyright (c) 2010, Jonathan Baldwin
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RECAP_X11CAPTURE_H
#define RECAP_X11CAPTURE_H

#include "RecapUtil.h"

#include <stdexcept>

extern "C"
{
#include <X11/Xatom.h>
#include <X11/cursorfont.h>
#include <X11/X.h>
#include <X11/keysymdef.h>
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include <X11/Xlibint.h>
#include <X11/Xcms.h>
#include <X11/Xutil.h>
#include <X11/Xresource.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xrender.h>
#include <X11/extensions/Xdamage.h>
#include <X11/extensions/XShm.h>
#include <sys/ipc.h>
#include <sys/shm.h>
}

namespace recap
{

class X11Capture
{
public:
    struct Params
    {
        enum TargetType_t
        {
            Screen,
            WindowByClass,
            WindowById,
            WindowBySelect
        } targetType;
        union Target_t
        {
            int screen;
            const char *windowClass;
            Window windowId;
        } target;
        bool useRegion;
        XRectangle region;
    };

    inline X11Capture ()
    {
      m_params = getDefaultParams();
    }
    inline const char *name() const
    {
        return "X11";
    }
    inline void setParams(void *params)
    {
      m_params = *((Params*) params);
    }
    inline int open()
    {
        m_dpy = XOpenDisplay(0);
        {
            int event_base, error_base, major_version = 0, minor_version = 2;
            if (!
                    (
                        (m_params.targetType == Params::Screen) ||
                        ((XCompositeQueryExtension(m_dpy, &event_base, &error_base)) &&
                         (XCompositeQueryVersion(m_dpy, &major_version, &minor_version),
                          (major_version > 0 || minor_version >= 2)))
                    )
               )
                rFatal("Failure to find sufficient "
                       "XComposite support");
            if (!XDamageQueryExtension(m_dpy, &m_damage_base, &error_base))
                rFatal("Failure to find sufficient "
                       "XDamage support");
            if (!XShmQueryExtension(m_dpy))
                rFatal("Failure to find sufficient "
                       "XShm support");
        }

        if (0 && m_params.targetType == Params::Screen)
	{
	  m_win = XRootWindow(m_dpy, m_params.target.screen);
	  m_pixmap = m_win;
	}
	else
        {
            switch (m_params.targetType)
            {
	    case Params::Screen:
	    {
	      m_win = XRootWindow(m_dpy, m_params.target.screen);
	    }
	    break;
            case Params::WindowBySelect:
            {
                m_win = grabWindow(m_dpy);
            }
            break;
            case Params::WindowById:
            {
                m_win = m_params.target.windowId;
            }
            break;
            default:
                rFatal("Window ???");
            };
            XGetWindowAttributes(m_dpy,m_win,&m_attr);
            XCompositeRedirectWindow(m_dpy, m_win, CompositeRedirectAutomatic);
            m_pixmap = XCompositeNameWindowPixmap(m_dpy,m_win);
        }
        m_image = XShmCreateImage(m_dpy,m_attr.visual,m_attr.depth,ZPixmap,(char*)0,&m_shmInfo,m_attr.width,m_attr.height);

        m_shmInfo.shmid = shmget(IPC_PRIVATE,m_image->bytes_per_line*m_image->height,IPC_CREAT|0777);
        m_shmInfo.shmaddr = m_image->data = (char*) shmat(m_shmInfo.shmid,0,0);
        m_shmInfo.readOnly = false;
	
        m_damage = XDamageCreate(m_dpy, m_pixmap, XDamageReportNonEmpty);

	if (!XShmAttach(m_dpy,&m_shmInfo))
	{
	  close();
	}
	char rgbmask [33];
	for(unsigned int i = 0; i < 32; i++)
	{
	  unsigned long m = 1<<(31-i);
	  rgbmask[i] = (m_image->red_mask & m) ? 'r' : ((m_image->green_mask & m) ? 'g' : ((m_image->blue_mask & m) ? 'b' : ('0')));
	}
	rgbmask[32] = '\0';
	  
	rDebug("X11 Window %ld caught: %dx%d@%dbpp (%d bytes per scanline, %s)", (long) m_win, m_image->width, m_image->height, m_image->bits_per_pixel, m_image->bytes_per_line, rgbmask);
	
#if 0
        std::cerr << "===XImage===" << std::endl;
        std::cerr << "width:" << m_image->width << std::endl;
        std::cerr << "height:" << m_image->height << std::endl;
        std::cerr << "bytes_per_line:" << m_image->bytes_per_line << std::endl;
        std::cerr << "bits_per_pixel:" << m_image->bits_per_pixel << std::endl;
        std::cerr << "depth:" << m_image->depth << std::endl;
        std::cerr << "bitmap_bit_order:" << m_image->bitmap_bit_order << std::endl;
        std::cerr << "bitmap_pad:" << m_image->bitmap_pad << std::endl;
        std::cerr << "bitmap_unit:" << m_image->bitmap_unit << std::endl;
        std::cerr << std::hex;
        std::cerr << "red_mask:" << m_image->red_mask << std::endl;
        std::cerr << "green_mask:" << m_image->green_mask << std::endl;
        std::cerr << "blue_mask:" << m_image->blue_mask << std::endl;
        std::cerr << std::dec;
        std::cerr << "===Attributes===" << std::endl;
        std::cerr << "width: " << m_attr.width << std::endl;
        std::cerr << "height: " << m_attr.height << std::endl;
        std::cerr << "depth: " << m_attr.depth << std::endl;
        std::cerr << "===PictFormat===" << std::endl;
        std::cerr << "id: " << m_pictFormat->id << std::endl;
        std::cerr << "type: " << m_pictFormat->type << std::endl;
        std::cerr << "depth: " << m_pictFormat->depth << std::endl;
        std::cerr << std::hex;
        std::cerr << (m_pictFormat->direct.alphaMask << m_pictFormat->direct.alpha) << std::endl;
        std::cerr << (m_pictFormat->direct.redMask << m_pictFormat->direct.red) << std::endl;
        std::cerr << (m_pictFormat->direct.greenMask << m_pictFormat->direct.green) << std::endl;
        std::cerr << (m_pictFormat->direct.blueMask << m_pictFormat->direct.blue) << std::endl;
        std::cerr << std::dec;
        std::cerr << "======" << std::endl;
#endif
	XShmGetImage(m_dpy,m_pixmap,m_image,0,0,AllPlanes);
	return 0;
    }
    inline void close()
    {
          XShmDetach(m_dpy,&m_shmInfo);
	  rDebug("x detached from shm");
	  XDestroyImage(m_image);
	  rDebug("image destroyed");

	  shmdt(m_shmInfo.shmaddr);

	  rDebug("process detached from shm");
	  shmctl(m_shmInfo.shmid, IPC_RMID, 0);
	  rDebug("shm destroyed");

	  if(m_params.targetType != Params::Screen)
	  {
	    XCompositeUnredirectWindow(m_dpy, m_win, CompositeRedirectAutomatic);
	    rDebug("window unredirected");
	  }

	  XCloseDisplay(m_dpy);
	  rDebug("dpy closed");

    }
    inline void handleEvents()
    {
      if(!XPending(m_dpy))
	return;
      XNextEvent(m_dpy, &m_event);
      {
	if((m_event.type) == (m_damage_base + XDamageNotify))
	{
	  XDamageNotifyEvent *e= (XDamageNotifyEvent*)(&m_event);
	  
	  XShmGetImage(m_dpy,m_pixmap,m_image,0,0,AllPlanes);
	  XDamageSubtract(m_dpy, e->damage, None, None);
	}
      }
    }
    inline int getBytesPerLine()
    {
      return m_image->bytes_per_line;
    }
    inline int getWidth()
    {
      return m_image->width;
    }
    inline int getHeight()
    {
      return m_image->height;
    }
    inline char* getFrame()
    {
      return m_image->data;
    }
    inline void ungetFrame()
    {
    }
private:
    static inline Params getDefaultParams()
    {
        Params p;
        p.targetType = Params::WindowBySelect;
        p.target.screen = 0;
        p.useRegion = 0;
        return p;
    }
    static inline Window grabWindow (Display *dpy)
    {
        int       scr;
        Window    root, rw;
        Cursor    cur;

        const int mask = ButtonPressMask | ButtonReleaseMask;

        scr = XDefaultScreen(dpy);
        root = XRootWindow(dpy,scr);

        cur = XCreateFontCursor(dpy, XC_trek);
        if (cur==None)
            rFatal("Failed creating window selection cursor");

        if (XGrabPointer(dpy, root, False, mask,
                         GrabModeSync, GrabModeAsync,
                         None, cur, CurrentTime) != GrabSuccess)
            rFatal("Failed grabbing the mouse pointer");

        {
            XEvent event;
            bool pressed = false;
            do
            {
                XAllowEvents(dpy,SyncPointer,CurrentTime),
                XWindowEvent(dpy,root,mask,&event);
                switch (event.type)
                {
                case ButtonPress:
                    rw = event.xbutton.subwindow;
                    pressed = true;
                    break;
                case ButtonRelease:
                    pressed = !pressed;
                }
            }
            while (pressed);
        }

        XUngrabPointer(dpy, CurrentTime);
        XFreeCursor(dpy,cur);
        XSync(dpy, 0);
        return rw;
    }

    Params m_params;
    Display *m_dpy;
    Window  m_win;
    XWindowAttributes m_attr;
    Pixmap m_pixmap;
    XShmSegmentInfo m_shmInfo;
    XImage *m_image;
    Damage m_damage;
    XEvent m_event;
    int m_damage_base;
};

}
#endif